//index.js
//获取应用实例
const product = require('../../api/product.js')
const banner = require('../../api/banner.js')
var app = getApp()
Page({
  data: {
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    product: [],
    product2: [],
    product3: [],
    baseline: false,
    index: 0,
    page: 0,
    limit: 10,
    isReachBottom: true
  },
  onLoad: function(options) {
    wx.showLoading({
      title: '正在加载'
    })
  },
  // 获取tab-index
  onChangeIndex(e) {
    console.log(e)
    this.setData({
      index: e.detail.index
    })
  },
  // 获取banner
  getBanners() {
    let page = 0
    let limit = 99999
    banner.getBanners(page, limit).then(res => {
      let data = []
      res.data.data.rows.forEach(value => {
        if(value.is_banner == 1) {
          data.push(value)
        }
      })
      this.setData({
        imgUrls: data
      })
    })
  },
  // 点击banner图跳转商品详情
  toDetail(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../productdetail/productdetail?id=' + id,
    })
  },
  // 获取热门商品
  getHotProducts() {
    product.getHotProducts().then(res => {
      if (res.data.code == 0) {
        res.data.data.forEach(value => {
          value.price = value.price.toFixed(2)
        })
        this.setData({
          product: res.data.data
        })
        wx.hideLoading()
      }
    })
  },
  // 获取最新商品
  getNewProducts() {
    product.getNewProducts().then(res => {
      if (res.data.code == 0) {
        res.data.data.forEach(value => {
          value.price = value.price.toFixed(2)
        })
        this.setData({
          product3: res.data.data
        })
        wx.hideLoading()
      }
    })
  },
  // 获取上架商品
  getStatusProducts() {
    let limit = 10
    let page = 0
    product.getStatusProducts(page, limit).then(res => {
      if (res.data.code == 0) {
        this.setData({
          product2: res.data.data
        })
        wx.hideLoading()
      }
    })
  },
  onShow: function() {
    app.setNum()
    this.getBanners()
    this.getHotProducts()
    this.getNewProducts()
    this.getStatusProducts()
  },
  onReachBottom() {
    if (this.data.isReachBottom) {
      if (this.data.index == 2) {
        let that = this
        this.data.page++
        let limit = this.data.limit
        let page = this.data.page
        this.setData({
          baseline: true
        })
        let product2 = this.data.product2
        product.getStatusProducts(page, limit).then(res => {
          if (res.data.data.length > 0) {
            product2 = product2.concat(res.data.data)
            that.setData({
              product2: product2
            })
          }else {
            this.setData({
              isReachBottom: false
            })
          }
        })
      }
    }
  },
  // 获取输入框焦点跳转搜索页面
  toSearch() {
    wx.navigateTo({
      url: '../search/search',
    })
  }
})